package router

import (
	"net/http"
	"order-pro/handler"

	"github.com/gin-gonic/gin"
)

func Router() *gin.Engine {

	r := gin.Default()
	r.Use(Cors())
	r.Static("/static", "./static")
	r.POST("/login", handler.Login)             // 用户登录
	r.POST("/role/nodeAdd", handler.RoleNodAdd) // 角色权限添加
	r.POST("/shop/add", handler.ShopAdd)        // 商品信息添加
	r.POST("/order/add", handler.OrderAdd)      // 订单添加
	r.GET("/user/role", handler.UserRole)       // 用户角色查询
	r.GET("/role/node", handler.RoleNode)       // 角色权限查询
	r.GET("/order/list", handler.OrderList)     // 订单列表
	r.GET("/order/detail", handler.OrderDetail) // 订单详情
	return r

}

func Cors() gin.HandlerFunc {

	return func(c *gin.Context) {
		method := c.Request.Method
		origin := c.Request.Header.Get("Origin")
		if origin != "" {
			c.Header("Access-Control-Allow-Origin", "*")
			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
			c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization")
			c.Header("Access-Control-Allow-Credentials", "true")
			c.Set("content-type", "application/json")
		}
		//放行所有OPTIONS方法
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}
		c.Next()
	}
}
